package cn.ydw.community.service.impl;

import cn.ydw.community.entity.LoginTicket;
import cn.ydw.community.entity.User;
import cn.ydw.community.dao.UserDao;
import cn.ydw.community.service.UserService;
import cn.ydw.community.util.CommonUtils;
import cn.ydw.community.util.CommunityConstant;
import cn.ydw.community.util.MailClient;
import cn.ydw.community.util.RedisKeyUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dw
 * @since 2020-10-18
 */
@Service
public class UserServiceImp extends ServiceImpl<UserDao, User> implements UserService, CommunityConstant {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;
//    private LoginTicketDao loginTicketDao;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private MailClient mailClient;

    @Value("${commons.domain.url}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public User selectUserById(Integer id) {
        User user = getCache(id);
        if (user == null){
            return initCache(id);
        }
        return user;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }
        if (user.getType() != 3 && user.getType()!= 4 && user.getType()!=5){
            map.put("typeMsg", "学校选择错误!");
            return map;
        }

        //验证账号
        User u = userDao.selectUserByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        u = userDao.selectByEmail(user.getEmail());
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }
        //注册用户
        user.setUsername(user.getUsername());
        user.setSalt(CommonUtils.generateUUID().substring(0, 5));
        user.setPassword(CommonUtils.MD5(user.getPassword() + user.getSalt()));
        user.setEmail(user.getEmail());
        user.setStatus(0);
        user.setType(user.getType());
        user.setCreateTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setActivationCode(CommonUtils.generateUUID());
        if (user.getType() == 3){
            user.setSchool("武汉华夏理工学院");
        }else if (user.getType() == 4){
            user.setSchool("武昌首义学院");
        }else if (user.getType() == 5){
            user.setSchool("汉口学院");
        }
        user.setGraduationTime(user.getGraduationTime());
        userDao.insert(user);

        //激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        String uri = domain + contextPath + "/activecode/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("uri", uri);
        //解析html文本为字符串 发送邮件
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);

        return map;
    }

    //激活
    @Override
    public int activation(int userId, String code){
        User user = userDao.selectUserById(userId);
        if (user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }else if (user.getActivationCode().equals(code)){
            userDao.updateStatus(userId, 1);
            return ACTIVATION_SUCCESS;
        }else{
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 用户登录
     */
    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        // 验证用户名密码不为空
        if (StringUtils.isBlank(username)){
            map.put("usernameMsg","用户名不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        User user = userDao.selectUserByName(username);
        // 验证账号是否存在
        if (user == null){
            map.put("usernameMsg", "该用户不存在");
            return map;
        }
        // 验证状态
        if (user.getStatus() == ACTIVATION_FAILURE){
            map.put("usernameMsg", "该账号未激活");
            return map;
        }

        //验证密码
        String md5 = CommonUtils.MD5(password + user.getSalt());
        if (!user.getPassword().equals(md5)){
            map.put("passwordMsg", "密码错误");
            return map;
        }
        //生成验证凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000L)
                .toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        loginTicket.setTicket(CommonUtils.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setUserId(user.getId());
//        loginTicketDao.insertLoginTicket(loginTicket);
        // 将loginTicket对象保存到redis中
        String ticketKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    /**
     * 根据ticket 查询用户信息
     */
    @Override
    public LoginTicket findLoginTicket(String ticket){
//        return loginTicketDao.selectLoginTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 退出用户修改凭证
     */
    @Override
    public void logout(String ticket){
//        return loginTicketDao.updateLoginTicket(ticket, 1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    /**
     * 修改用户图片
     * @param userId 用户id
     * @param headerUri 用户图像URI
     * @return
     */
    @Override
    public int updateHeader(Integer userId, String headerUri){
//        return userDao.updateHeader(userId, headerUri);
        int i = userDao.updateHeader(userId, headerUri);
        clearCache(userId);  // 修改用户信息时删除缓存
        return i;
    }


    /**
     * 通过用户名查找对象
     *
     * @param username
     */
    @Override
    public User findUserByName(String username) {
        return userDao.selectUserByName(username);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.selectUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()){
                    case 1 : return AUTHORITY_ADMIN;
                    case 2 : return AUTHORITY_MODERATOR;
                    default : return AUTHORITY_USER;
                }
            }
        });
        return list;
    }

    @Override
    public int updatePassword(Integer userId, String newPassword) {
        int i = userDao.updatePassword(userId, newPassword);
        clearCache(userId);
        return i;
    }

    // 1.优先从缓存中取值
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2.取不到时初始化缓存数据
    private User initCache(int userId) {
        User user = userDao.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    // 3.数据变更时清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }
}
